import { useRef, forwardRef, useImperativeHandle } from 'react';

//父组件
function A1() {
  const a2 = useRef(null);
  if (a2.current) {
    a2.current.func(); //父组件调用子组件
  }
  return (
    <div>
      a1
      <A2 ref={a2} />
    </div>
  );
}

//子组件
const A2 = forwardRef((props, ref) => {
  const func = () => {
    console.log('a2');
  };
  //自定义暴露子组件方法
  useImperativeHandle(ref, () => {
    return {
      func,
    };
  });
  return <div ref={ref}>a2</div>;
});

export default A1;
